package com.example.administrator.nurse.NetWork;

/**
 * Created by Administrator(林冠宏) on 2015/11/23.
 *
 */

import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.nurse.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;


public class internetHelper {

    private static int timeOutCount = 0;
    private static final int IO_BUFFER_SIZE = 10 * 1024;

    public static boolean checkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) common.context.getSystemService(common.context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            Log.d("zzzzz","无法连接网络");
            Toast.makeText(common.context,"无法连接网络!",Toast.LENGTH_LONG).show();
            return false;
        }else{
            return true;
        }
    }

    //get data
    public synchronized static String getStringFromUrlOnHttpRULconnection(String url) throws IOException{ // 联网 核心
        String json = null;
        URL myUrl = null;
        try {
            myUrl = new URL(url);
            HttpURLConnection myUrlConnect = (HttpURLConnection) myUrl.openConnection();
            myUrlConnect.setConnectTimeout(10 * 1000);//7秒超
            myUrlConnect.setRequestMethod("GET");
            //byte[] data = StreamTool.readInputStream(myUrlConnect.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(myUrlConnect.getInputStream(), "UTF-8"), 8);//100 M
            StringBuilder info = new StringBuilder();//定义字符容器
            String line = null;//用来保存提取出的每行数据
            while ((line = reader.readLine()) != null) {//保证读到的每行数据不为null
                info.append(line + "\n");//每行相加
            }
            json = info.toString();
            reader.close();
        }catch(SocketTimeoutException e){
            timeOutCount++;
            if(timeOutCount==6){
                return "timeout";
            }
            return getStringFromUrlOnHttpRULconnection(url);
        } catch (Exception e) {

        }
        return json;
    }

    //------------------------------------------------------------------------------------------------------

    public static ArrayList<NameValuePair> initPostDataSets(String[] keys,String[] values) {
        ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();//定义一个键值对来行的数组容器
        for(int i=0;i<keys.length;i++){
            data.add(new BasicNameValuePair(keys[i],values[i]));//这里设置php文件接收的Order，例如 $_REQUEST["Order"]，根据你的php自己定义的来写
        }
        return data;//返回设置好了容器
    }

    public static String postDataToServer(String url,String[] keys,String[] values) {
        try {
            UrlEncodedFormEntity body = new UrlEncodedFormEntity(initPostDataSets(keys,values),"UTF-8");
            return sendCommonFunction(url,body);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sendCommonFunction(String url,UrlEncodedFormEntity body){
        String json="-1";
        InputStream GetContentFromDb = null;//定义一个保存输入流的变量
        try {
            HttpClient http = new DefaultHttpClient();//开启http服务
            HttpPost post = new HttpPost(url);//传入url，初始化要post数据的url
            post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//也是为了解决 post中文的乱码问题
            post.setEntity(body);
            HttpResponse response = http.execute(post);//这里才正真地进行访问，带着上面设置的数据
            HttpEntity responseFromDb = response.getEntity();//接受返回的实体
            GetContentFromDb = responseFromDb.getContent();//接受实体内容，并保存到输入流对象中
        } catch (Exception e) {
            Log.d("zzzzz", e.toString());
        }
        try {
            assert GetContentFromDb != null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(GetContentFromDb, "UTF-8"), 8);//取回的内容，按照 utf8
            //上面的这句作用是把输入流里面的内容进行编码，第二个最好设置UTF-8，要和你的mysql表的一样，如果用iso-8859-1可能会抛出乱码错误
            StringBuilder info = new StringBuilder();//定义字符容器
            String line = null;//用来保存提取出的每行数据
            while ((line = reader.readLine()) != null) {//保证读到的每行数据不为null
                info.append(line + "\n");//每行相加
            }
            GetContentFromDb.close();//关闭
            json = info.toString();//数据转化
        } catch (Exception e) {
            Log.d("*****", e.toString());
        }
        Log.d("*****", "3");
        return json;
    }

    // upLoadPic
    public synchronized static void uploadPic(String uploadUrl,String filename,Bitmap bit){ //同一时间只能上传�?张，必须�? synchronized
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        int compress=100;
        try{
            URL url = new URL(uploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置每次传输的流大小，可以有效防止手机因为内存不足崩�?
            // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲�? HTTP 请求正文的流�?
            httpURLConnection.setChunkedStreamingMode(256 * 1024);// 256K
            // 允许输入输出�?
            httpURLConnection.setConnectTimeout(10*1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            // 使用POST方法
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);

            // 发头
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
                    + filename.substring(filename.lastIndexOf("/") + 1)
                    + "\""
                    + end);
            dos.writeBytes(end);
            Log.d("zzzzz","send");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bit.compress(Bitmap.CompressFormat.JPEG, compress, baos);
            while (baos.toByteArray().length / 1024 > 500) {
                Log.d("zzzzz","compress time ");
                baos.reset();
                compress -= 10;
                if(compress==0){
                    bit.compress(Bitmap.CompressFormat.JPEG, compress, baos);
                    break;
                }
                bit.compress(Bitmap.CompressFormat.JPEG, compress, baos);
            }
            InputStream fis = new ByteArrayInputStream(baos.toByteArray());
            // FileInputStream fis = new FileInputStream(srcPath);
            byte[] buffer = new byte[10*1024]; // 8k+2k
            int count = 0;
            // 读取文件
            while ((count = fis.read(buffer)) != -1) {
                // 传图片比
                //common.Log("-----" + count);
                dos.write(buffer, 0, count);
            }
            fis.close();
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();

            // 获取返回
            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();

            Log.d("zzzzz",result);
            dos.close();
            is.close();
        } catch (Exception e){
            e.printStackTrace();
            Log.d("zzzzz", e.toString());
        }
    }
    
}
